import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Redirect, useLocation } from 'react-router';

export default function(props) {
  const dispatch = useDispatch();
  const { pathname } = useLocation();
  const { user } = useSelector(state => state.user);
  useEffect(() => {
    if (!user.trim()) {
      dispatch({
        type: 'user/setPrevPath',
        prevPath: pathname,
      });
    }
  }, [user]);

  if (user) {
    return <>{props.children}</>;
  }

  return <Redirect to="/login" />;
}
